package com.jixin.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtils{

   
    /**
     * 封装HTTP POST方法
     * @param 请求路径
     * @param 请求参数
     */
    public static String post(String url, Map<String, String> paramMap) {
    	HttpPost httpPost = new HttpPost(url);
        try
        {
        	List<NameValuePair> formparams = setHttpParams(paramMap);
        	UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");
        	httpPost.setEntity(param);
        	HttpResponse response = HttpClientHelper.getClient().execute(httpPost);
        	if(response.getStatusLine().getStatusCode() == 200)
        	{
        		String result = EntityUtils.toString(response.getEntity());
        		return result;
        	}
        }catch(Exception e)
        {
        	e.printStackTrace();
        	httpPost.abort();
        }finally
        {
        	httpPost.releaseConnection();
        }
        return null;
    }

    /**
     * 设置请求参数
     * @param
     * @return
     */
    private static List<NameValuePair> setHttpParams(Map<String, String> paramMap) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> set = paramMap.entrySet();
        for (Map.Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return formparams;
    }


   
   
}
